package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: SupplierServiceImpl
 * Package: com.atguigu.jxc.service.impl
 * Description:
 *
 * @Author 梅超凡
 * @Create 2025/2/21 14:08
 * @Version 1.0
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierDao supplierDao;

    /**
     * 分页查询供应商信息
     * @param page 页码
     * @param rows 行数
     * @param supplierName 供应商名称
     * @return Map<String, Object>
     */
    @Override
    public Map<String, Object> supplierList(Integer page, Integer rows, String supplierName) {
        Map<String, Object> resultMap = new HashMap<>();

        page = (page - 1) * rows;
        List<Supplier> suppliers = supplierDao.supplierList(page, rows, supplierName);
        int total = supplierDao.getSupplierCount();
        resultMap.put("rows", suppliers);
        resultMap.put("total", total);
        return resultMap;
    }

    /**
     * 保存供应商信息
     * @param supplier 供应商信息
     * @return ServiceVO<Object>
     */
    @Override
    public ServiceVO<Object> saveOrUpdate(Supplier supplier) {
        //获取供应商ID
        Integer supplierId = supplier.getSupplierId();
        //定义结果变量
        int i = 0;
        //ID为空，插入供应商信息
        if (supplierId == null) {
            i = supplierDao.saveSupplier(supplier);
        }else {
            //否则根据ID更新供应商信息
            i = supplierDao.updateSupplier(supplierId, supplier);
        }
        if (i > 0){
            return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, i);
        }
        return new ServiceVO<>(ErrorCode.ADD_ERROR_CODE, ErrorCode.ADD_ERROR_MESS, i);
    }

    /**
     * 删除供应商信息(支持批量删除)
     * @param ids 供应商id串
     * @return ServiceVO<Object>
     */
    @Override
    public ServiceVO<Object> deleteById(String ids) {
        String[] splitIds = ids.split(",");
        System.out.println("本次删除"+splitIds.length + "条数据");
        //生成Id集合
        List<Integer> listIds = new ArrayList<>();
        for (String id : splitIds) {
            listIds.add(Integer.parseInt(id));
        }
        int count = supplierDao.deleteSupplierById(listIds);
        if (count > 0){
            return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, count);

        }
        return new ServiceVO<>(ErrorCode.DELETE_ERROR_CODE, ErrorCode.DELETE_ERROR_MESS, count);
    }
}
